package com.buildings.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.buildings.R;
import com.buildings.base.BaseActivity;
import com.buildings.base.BaseApplication;
import com.buildings.bean.LocalBean;
import com.buildings.bean.LocationEntity;
import com.buildings.bean.VolcanicSvyPointDbEntity;
import com.buildings.map.ArcGisUtil;
import com.buildings.map.TianDiMapUtils;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.WebTiledLayer;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.view.BackgroundGrid;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 轨迹采集页面
 */
public class TrajectoryActivity extends BaseActivity {
    @BindView(R.id.gis_map)
    MapView mapView;
    @BindView(R.id.tv_title)
    TextView tvTitle;

    private ArcGisUtil arcGisUtil;
    private ArcGISMap map;
    private WebTiledLayer vectorBaseMap;
    private WebTiledLayer vectorBaseMapAnno;
    private Point locationPoint;
    private int i = 0;
    private long _id;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trajectory);
        ButterKnife.bind(this);
        initMap();
        initAndroidLocation();
        initData();
    }

    private void initData() {
        if (!getIntent().hasExtra("_id")) {
            finish();
        }
        _id = getIntent().getLongExtra("_id", -1);
        getLocatlData();
    }

    private void getLocatlData() {
        List<LocationEntity> locationEntities
                = BaseApplication.getInstance().getDaoSession().loadAll(LocationEntity.class);
        for (int i = 0; i < locationEntities.size(); i++) {
            if (_id == locationEntities.get(i).get_id()) {
                String pointArr = locationEntities.get(i).getPoint();
                Log.e("wangchao",pointArr);
                if (TextUtils.isEmpty(pointArr)){
                    return;
                }
                String[] split = pointArr.split(";");
                showLine(split);
            }
        }
    }

    public void initMap() {
        tvTitle.setText("轨迹");
        arcGisUtil = new ArcGisUtil(this, mapView);
        map = new ArcGISMap();

        vectorBaseMap = TianDiMapUtils.getTianDiMap(TianDiMapUtils.MapType.URL_CN_VECTORBASEMAP);
        vectorBaseMapAnno = TianDiMapUtils.getTianDiMap(TianDiMapUtils.MapType.URL_CN_VECTORBASEMAP_ANNOTATION);

        List<WebTiledLayer> vectorBaseMapLayerList = new ArrayList<>();
        vectorBaseMapLayerList.add(vectorBaseMap);
        vectorBaseMapLayerList.add(vectorBaseMapAnno);

        map.setMaxScale(TianDiMapUtils.getSCALES()[TianDiMapUtils.getSCALES().length - 1]);
        mapView.setMap(map);
        mapView.setAttributionTextVisible(false);
        mapView.setBackgroundGrid(new BackgroundGrid(Color.WHITE, Color.WHITE, 0, 2f));
        map.getOperationalLayers().addAll(vectorBaseMapLayerList);

        vectorBaseMap.loadAsync();
        vectorBaseMapAnno.loadAsync();
    }

    public void initAndroidLocation() {
        LocationDisplay locationDisplayManager = mapView.getLocationDisplay();//获取定位类
        locationDisplayManager.setShowLocation(true);
        locationDisplayManager.setShowLocation(true);
        locationDisplayManager.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                locationPoint = locationChangedEvent.getLocation().getPosition();
                if (locationPoint == null) {
                    return;
                }
                if (i == 1) {
                    moveMapCenter(locationPoint);
                    i++;
                }
            }
        });
        locationDisplayManager.startAsync();//开始定位
    }

    private void moveMapCenter(Point point) {
        mapView.setViewpointCenterAsync(point, TianDiMapUtils.getSCALES()[16]);
    }

    private void showLine(String[] pointArr) {
        if (pointArr.length == 0){
            return;
        }
        List<Point> points = new ArrayList<>();
        for (int i = 0;i<pointArr.length;i++){
            String[] pointStr = pointArr[i].split(",");
            double lat = Double.parseDouble(pointStr[0]);
            double lon = Double.parseDouble(pointStr[1]);
            Point point = new Point(lat,lon, SpatialReferences.getWgs84());
            points.add(point);
        }
        drawArcgisLine(points);
    }

    /**
     * map画线
     */
    private void drawArcgisLine(List<Point> points) {
        PointCollection pointCollection = new PointCollection(points);
        Polyline mPolyline = new Polyline(pointCollection);//点画线，mPoints为坐标集合
        GraphicsOverlay graphicsOverlayPump = new GraphicsOverlay();
        mapView.getGraphicsOverlays().add(graphicsOverlayPump);
        SimpleLineSymbol lineSym =
                new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.task_status_unfinished), 5);
        Graphic graphicTrail = new Graphic(mPolyline, lineSym);
        graphicsOverlayPump.getGraphics().add(graphicTrail);
    }
}
